﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using StockFinder.Model;
using StockFinder.Services.Brokers;
using StockFinder.Model.Enumerations;

namespace StockFinder.Services.Extractors.EODData
{
    /*
     * http://www.eoddata.com/Data/symbollist.aspx?e=NYSE
     * http://www.eoddata.com/Data/symbollist.aspx?e=NASDAQ
     */

    public class EODDataSymbolListExtractor : ISymbolListExtractor
    {
        public List<Symbol> GetSymbolList()
        {
            List<Symbol> symbols = new List<Symbol>();

            //1. login into site
            EODDATABroker broker = new EODDATABroker();
            broker.Login();

            //must be logged in so have the valid cookie container
            if (broker.LoggedIn)
            {
                //download the nasdaq list
                string nasdaqList = broker.DownloadSymbolList("http://www.eoddata.com/Data/symbollist.aspx?e=NASDAQ");

                List<string> nasdaqSymbols = ExtractSymbols(nasdaqList);

                foreach (var nasdaqSymbol in nasdaqSymbols)
                {
                    symbols.Add(new Symbol()
                    {
                        Name = nasdaqSymbol,
                        Exchange = Exchange.NASDAQ
                    });
                }

                //download the nyse list
                string nyseList = broker.DownloadSymbolList("http://www.eoddata.com/Data/symbollist.aspx?e=NYSE");

                List<string> nyseSymbols = ExtractSymbols(nyseList);

                foreach (var nyseSymbol in nyseSymbols)
                {
                    symbols.Add(new Symbol()
                    {
                        Name = nyseSymbol,
                        Exchange = Exchange.NYSE
                    });
                }
            }

            return symbols;
        }

        public List<string> ExtractSymbols(string pageSource)
        {
            List<string> symbols = new List<string>();
                
            string symbol = string.Empty;

            if (!string.IsNullOrEmpty(pageSource))
            {
                string[] lines = pageSource.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                      
                foreach (var line in lines)
                {
                    string[] symbolLines = line.Split(new string[] { "\t" }, StringSplitOptions.None);

                    symbol = symbolLines[0];

                    if (!symbol.Contains(".") &&
                        !symbol.Contains("-") &&
                        !string.IsNullOrEmpty(symbol) &&
                        symbol != "Symbol")
                    {
                        symbols.Add(symbolLines[0]);
                    }
                }
            }

            return symbols;
        }        
    }
}
